package com.wolfking.converter.transform.extend;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wolfking.converter.transform.AbstractExtendTransform;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;

@Slf4j
public class MapKvTransform extends AbstractExtendTransform<String> {

    private Map<String, String> config = Maps.newHashMap();


    public MapKvTransform() {
        this("{}");
    }

    public MapKvTransform(String arg) {
        try {
            config = new Gson().fromJson(arg, new TypeToken<Map<String, String>>() {
            }.getType());
        } catch (Exception e) {
            log.warn("", e);
        }
    }

    @Override
    public String transform(Object value) throws Exception {
        if (Objects.isNull(value)) {
            return "";
        } else {
            String toString = value.toString();
            return config.getOrDefault(toString, config.getOrDefault("default", toString));
        }
    }

    @Override
    public String getExampleConfig() {
        return "{\n" +
                "\t\"1\": \"今天\",\n" +
                "\t\"2\": \"最近两天\",\n" +
                "\t\"3\": \"最近三天\",\n" +
                "\t\"default\": \"最近7天\"\n" +
                "}";
    }

    @Override
    public String getExampleConfigDesc() {
        return "json转map，默认返回default";
    }
}
